﻿function addItems() {
    var title = $("#title");
    if (title.val() == "") {
        alert("请输入事项");
        return;
    }
    var item = { "title": title.val(), "done": false };
    var data = getData();
    data.push(item);
    saveData(data);
    var form = $("#form");
    form.reset();
    showData();
}


function getData() {
    var data = localStorage.getItem("todoList");
    if (data != null) {
        return JSON.parse(data);
    }
    else {
        return [];
    }
}

function svaeSort() {
    var todolist = $("#todoList");
    var donelist = $("#doneList");
    var ts = todolist.getElementByTagName("p");
    var ds = donelist.getElementByTagName("p");
    var data = [];
    for (i = 0; i < ts.length; i++) {
        var todo = { "title": ts[i].innerHTML, "done": false };
        data.unshift(todo);
    }
    for (i = 0; i < ds.length; i++) {
        var todo = { "title": ds[i].innerHTML, "done": true };
        data.unshift(todo);
    }
    saveData(data);
}



function saveData(data) {
    localStorage.setItem("todoList", JSON.stringify(data));
}


function changeStatue(index){
    var data = getData();
    data[index].done = !data[index].done;

    saveData(data);
    showData();
}

function deleteItem(index) {
    var data = getData();
    data.splice(index, 1);
    saveData(data);
    showData();
}

function showData() {
    var table = $("#todoList");
    var tableTwo = $("#doneList");
    var data = localStorage.getItem("todoList");
    if (data != null) {
        var todoList = JSON.parse(data);
        var todoCount = 0;
        var doneCount = 0;
        var todoString = "<tr><th></th><th></th><th></th></tr>";
        var doneString = "<tr><th></th><th></th><th></th></tr>";
        for (var i = 0; i < todoList.length; i++) {
            if (!todoList[i].done) {
                todoString += "<tr><td><input type=\"checkbox\" id=\"lala\" onclick=\"changeStatue(" + i + ")\"/></td><td>" + todoList[i].title +
                    "</td><td>" + "</td><td style=\"cursor:pointer\" onclick=\"deleteItem(" + i + ")\">删除</td></tr>";
                todoCount++;
            }
            else {
                doneString += "<tr><td><input type=\"checkbox\" id=\"lala\" onclick=\"changeStatue(" + i + ")\"/></td><td>" + todoList[i].title +
                    "</td><td>" + "</td><td style=\"cursor:pointer\" onclick=\"deleteItem(" + i + ")\">删除</td></tr>";
                doneCount++;
            }
        }
        table.html(todoString);
        todocount.innerHTML = todoCount;
        tableTwo.html(doneString);
        donecount.innerHTML = doneCount;
        allcount.innerHTML = todoCount + doneCount;
    }
    else {
        table.html("");
        tableTwo.html("");
        todocount.innerHTML = 0;
        donecount.innerHTML = 0;
        allcount.innerHTML = 0;
    }
}


function clear() {
    localStorage.clear();
    showData();
}


$(document).ready(function () {
    showData();
})